package com.ebay.contest.gfour.common;

import java.util.HashMap;

import org.apache.log4j.Logger;

import com.ebay.services.finding.SearchItem;
import com.ebay.services.finding.SearchResult;

public class ApiResultUtils {

    private static Logger logger = Logger.getLogger(ApiResultUtils.class);

    public static ApiResult convertEbayResultToOurFormat(SearchResult searchResult,
            HashMap<Integer, GeoLocation> zipCodeMapper) {
        ApiResult result = new ApiResult();

        for (SearchItem searchItem : searchResult.getItem()) {
            String postalCode = searchItem.getPostalCode();
            if (postalCode == null || postalCode.isEmpty()) {
                logger.debug("Item [" + searchItem.getTitle() + "] ignored because no postal code is available.");
                continue;
            }
            GeoLocation location = zipCodeMapper.get(Integer.parseInt(postalCode));
            if (location == null) {
                logger.debug("GeoLocation information for postal code [" + searchItem.getPostalCode()
                        + "] is not available.");
                continue;
            }
            ApiResultItem resultItem = new ApiResultItem(searchItem);
            resultItem.setLatitude(location.getLatitude());
            resultItem.setLongitude(location.getLongitude());

            result.getItems().add(resultItem);
        }

        return result;
    }
}
